﻿using AchieveBLL;
using AchieveCommon;
using AchieveEntity;
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Reporting.WebForms;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using AchieveManageWeb.Models;
//create by Ben
//图纸管理
//Modification time:2020.4.17

namespace AchieveManageWeb.Controllers
{
    [AchieveManageWeb.App_Start.JudgmentLogin]
    public class DrawController : Controller
    {

        /// <summary>
        /// 下发图纸
        /// </summary>
        /// <returns></returns>
        public ActionResult issueDraw() {
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            string drawId = Request["drawId"] == null ? "" : Request["drawId"];
            if (drawId=="")
            {
                return null;
            }
            string remark = Request["remark"] == null ? "" : Request["remark"];
            //string claimTime = string.IsNullOrWhiteSpace(Request["claimTime"]) ? null : Request["claimTime"]; 
            string issueTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
            string issueBy = uInfo.AccountName;
            string mainItemCode = Request["mainItemCode"] == null ? "" : Request["mainItemCode"];
            string mainItemName = Request["mainItemName"] == null ? "" : Request["mainItemName"];
            string subItemCode = Request["subItemCode"] == null ? "" : Request["subItemCode"];
            string subItemName = Request["subItemName"] == null ? "" : Request["subItemName"];
            string projectID = Request["projectID"] == null ? "" : Request["projectID"];
            int drawCount = Request["drawCount"] == null ? 0 : Convert.ToInt32(Request["drawCount"]);
            string sql = @"insert into tbDrawMgr(drawId,mainItemCode,mainItemName,subItemCode,subItemName,issueTime,issueBy,remark,projectID,drawCount) 
values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')";

            sql = string.Format(sql, drawId, mainItemCode, mainItemName, subItemCode, subItemName, issueTime, issueBy, remark, projectID, drawCount);
            if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
            {
                return Content("{\"msg\":\"下发成功\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"下发失败.\",\"success\":false}");
            }
        
        }
        public ActionResult delDraw() {
            string drawId = Request["drawId"] == null ? "" : Request["drawId"];
           // string type = Request["type"] == null ? "confirm" : Request["type"];
            if (drawId == "")
            {
                return null;
            }
            string sql = @"delete tbDrawMgr  WHERE drawId = '{0}'";
                sql = string.Format(sql, drawId);
                if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
                {
                    return Content("{\"msg\":\"删除成功\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"删除失败.\",\"success\":false}");
                }
        
        }

        /// <summary>
        /// 确认图纸
        /// </summary>
        /// <returns></returns>
        public ActionResult confirmDraw()
        {
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            string drawId = Request["drawId"] == null ? "" : Request["drawId"];
            string type = Request["type"] == null ? "confirm" : Request["type"];
            if (drawId == "")
            {
                return null;
            }
            string sql = "";
            if (type == "unConfirm")
            {
                sql = @"update tbDrawMgr SET confirmTime = '', confirmBy = '' WHERE drawId = '{0}'";

                sql = string.Format(sql, drawId);
                if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
                {
                    return Content("{\"msg\":\"取消确认成功\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"取消确认失败.\",\"success\":false}");
                }
            }

            string remark = Request["remark"] == null ? "" : Request["remark"];
            //string claimTime = string.IsNullOrWhiteSpace(Request["claimTime"]) ? null : Request["claimTime"]; 
            string confirmTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
            string confirmBy = uInfo.AccountName;
            sql = @"update tbDrawMgr SET confirmTime = '{0}', confirmBy = '{1}' WHERE drawId = '{2}'";

            sql = string.Format(sql, confirmTime, confirmBy, drawId);
            if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
            {
                return Content("{\"msg\":\"确认成功\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"确认失败.\",\"success\":false}");
            }

        }

        /// <summary>
        /// 调整图纸数量
        /// </summary>
        /// <returns></returns>
        public ActionResult adjDrawCount()
        {
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            string drawId = Request["drawId"] == null ? "" : Request["drawId"];
            string type = Request["type"] == null ? "confirm" : Request["type"];
            int adjCount = Request["adjCount"] == null ? 0 : Convert.ToInt32(Request["adjCount"]);
            if (drawId == "")
            {
                return null;
            }
            string adjTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
            string adjBy = uInfo.AccountName;
            string sql =   @"update tbDrawMgr SET adjCount = {0}, adjBy = '{1}',adjTime = '{2}'  WHERE drawId = '{3}'";

            sql = string.Format(sql, adjCount,adjBy,adjTime, drawId);
            if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
            {
                return Content("{\"msg\":\"调整成功\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"调整失败.\",\"success\":false}");
            } 

        }


        /// <summary>
        /// 图纸列表
        /// </summary>
        /// <returns></returns>
        public ActionResult getDrawList()
        {
            string strWhere = "1=1 ";
            string sort = Request["sort"] == null ? "issueTime" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];
            string projectID = Request["projectID"] == null ? "" : Request["projectID"];
            
            //string period = Request["period"] == null ? "" : Request["period"];
            if (projectID != "")
            {
                strWhere += string.Format("and projectID='{0}' ", projectID);
            } 
            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量

            string content = "";
            int totalCount;   //输出参数 
            string columns = @"
mainitemcode,
mainItemName,
subItemCode,
subItemName,
drawId,
drawName,
checkTime,
checkBy,
issueTime,
issueBy,
confirmTime,
confirmBy,
remark,
projectID,
drawCount,
adjCount
";
            DataTable dt = AchieveCommon.SqlPagerHelper.GetPagerBySQL(SqlHelper.connStr, "tbDrawMgr", columns, sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
            string strJson = AchieveCommon.JsonHelper.ToJson(dt);
            content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            return Content(content);

        }


        
        ///以下代码不用
        
        //
        // GET: / /
        public ActionResult Index()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "Bom—Index")); //日志记录
            return View();
        }
       



        /// <summary>
        /// 用于FitemSearchModel视图的物料搜索
        /// </summary>
        /// <returns></returns>
        public ActionResult getFitemStandard()
        {
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "FName" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];

            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量
            // string FBillNo = Request["FBillNo"] == null ? "" : Request["FBillNo"];
            string FName = Request["FName"] == null ? "" : Request["FName"];
            string FModel = Request["FModel"] == null ? "" : Request["FModel"];
            int fbominterid = string.IsNullOrWhiteSpace(Request["fbominterid"]) ? 0 : Convert.ToInt32(Request["fbominterid"]);
            if (fbominterid > 0)
            {
                strWhere += string.Format(" and b.FItemID = {0}", fbominterid);
            }
            if (FName != "")
            {
                strWhere += string.Format(" and b.FName like '%{0}%'", FName);
            }
            if (FModel != "")
            {
                strWhere += string.Format(" and b.FModel like '%{0}%'", FModel);
            }

            int totalCount;
            string tablename = "t_ICItemStandard a left join t_ICITEMCORE b on a.FItemID=b.FItemID";
            string innercolumns = " a.FItemID,a.FstandardCost,a.FstandardManHour,b.FName,b.FModel,b.FNumber,b.FOrderPrice";
            string outcolumns = "FItemID,FstandardCost,FstandardManHour,FName,FModel,FOrderPrice";
            string sort1 = "a.FItemID desc";
            DataTable dt = SqlHelper.GetPagerDataTable(tablename, innercolumns, outcolumns, pageindex, pagesize, strWhere, sort1, out totalCount, true);

            string strJson = JsonHelper.ToJson(dt);
            string content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            return Content(content);
        }



        public ActionResult getBomData()
        {
            int itemid = string.IsNullOrWhiteSpace(Request["itemid"]) ? 0 : Convert.ToInt32(Request["itemid"]);          
            //BomBLL bb = new BomBLL();
            bomTree bt = new bomTree();
            bt = BomBLL.getBomTreeByItemID(itemid);
            string json = BomBLL.bomTree2Json(bt);               
            return Content(string.Format("[{0}]", json));
        }

        /// <summary>
        /// bom树形结构数据转换为json
        /// </summary>
        /// <param name="bt"></param>
        /// <returns></returns>
        public static string bomTree2Json(bomTree bt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append(string.Format("\"name\":\"{0}\",", bt.name));
            sb.Append(string.Format("\"FinterID\":\"{0}\",", bt.FinterID));
            sb.Append(string.Format("\"FItemID\":\"{0}\",", bt.FItemID));
            sb.Append(string.Format("\"FName\":\"{0}\",", bt.FName));
            sb.Append(string.Format("\"FNumber\":\"{0}\",", bt.FNumber));

            sb.Append(string.Format("\"FModel\":\"{0}\",", bt.FModel));

            sb.Append(string.Format("\"FQty\":{0},", bt.FQty));
            sb.Append(string.Format("\"FOrderPrice\":{0},", bt.FOrderPrice));
            sb.Append(string.Format("\"itemPrice\":{0},", bt.itemPrice));//材料价格 
            sb.Append(string.Format("\"worktime\":{0},", bt.worktime));//工时  
            sb.Append(string.Format("\"fnetweight\":{0},", bt.fnetweight));//净重  
            sb.Append(string.Format("\"FGrossWeight\":{0},", bt.FGrossWeight));//净重 _最新 


            sb.Append(string.Format("\"value\":{0}", bt.value));//根据需要取值，目前不用
            if (bt.children != null)
            {
                sb.Append(string.Format(",\"children\":{0}", getnodejson(bt.children)));
            }
            sb.Append("}");

            return sb.ToString();
            //sb.Append(string.Format("children"))       
        }

        //bom转为json的递归函数
        private static string getnodejson(List<bomTree> list)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (bomTree item in list)
            {
                StringBuilder sb1 = new StringBuilder();
                sb1.Append("{");
                sb1.Append(string.Format("\"name\":\"{0}\",", item.name));
                sb1.Append(string.Format("\"FinterID\":\"{0}\",", item.FinterID));
                sb1.Append(string.Format("\"FItemID\":\"{0}\",", item.FItemID));
                sb1.Append(string.Format("\"FName\":\"{0}\",", item.FName));
                sb1.Append(string.Format("\"FModel\":\"{0}\",", item.FModel));
                sb1.Append(string.Format("\"FNumber\":\"{0}\",", item.FNumber));



                sb1.Append(string.Format("\"FQty\":{0},", item.FQty));
                sb1.Append(string.Format("\"FOrderPrice\":{0},", item.FOrderPrice));
                sb1.Append(string.Format("\"itemPrice\":{0},", item.itemPrice));//材料价格 
                sb1.Append(string.Format("\"worktime\":{0},", item.worktime));//工时  
                sb1.Append(string.Format("\"fnetweight\":{0},", item.fnetweight));//净重  
                sb1.Append(string.Format("\"FGrossWeight\":{0},", item.FGrossWeight));//净重                  
                sb1.Append(string.Format("\"value\":{0}", item.value));

                if (item.children != null)
                {
                    sb1.Append(string.Format(",\"children\":{0}", getnodejson(item.children)));
                }

                sb1.Append("},");
                sb.Append(sb1.ToString());

            }
            sb.Replace(',', ']', sb.Length - 1, 1);
            return sb.ToString();
        }

      
  public FileStreamResult ExportExcel()
        {

            //string FItemID = Request.Params["FItemID"];//获取数据视图类型 
            
            //int adjust =Convert.ToInt32( Request.Params["adjust"]);
           
            DataTable dt=new DataTable();//输出表格

            int itemid = string.IsNullOrWhiteSpace(Request["FItemID"]) ? 0 : Convert.ToInt32(Request["FItemID"]);          
            //bomTree bt = new bomTree();
            //bt = BomBLL.getBomTreeByItemID(itemid);
            //dt = BomBLL.bomTree2Table(bt);
            dt = BomBLL.getBomTableByItemID(itemid);

            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheetFFInterID,FFItemID,FFName,FFmodel,FItemID,worktime,FName,FNumber,FModel,FOrderPrice,fnetweight,FGrossWeight,BomLevel
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            NPOI.SS.UserModel.IRow row0 = sheet1.CreateRow(0);
           string s= dt.Columns[1].ColumnName;
            //row0.CreateCell(0).SetCellValue("序号");
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                row0.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);  
            }
            //row0.CreateCell(1).SetCellValue("父bomID");
            //row0.CreateCell(2).SetCellValue("父物料ID");
            //row0.CreateCell(3).SetCellValue("父物料名称");
            //row0.CreateCell(4).SetCellValue("父物料型号");
            //row0.CreateCell(5).SetCellValue("物料ID");
            //row0.CreateCell(6).SetCellValue("工时");
            //row0.CreateCell(7).SetCellValue("物料名称");
            //row0.CreateCell(8).SetCellValue("物料编码");
            //row0.CreateCell(9).SetCellValue("规格型号");
            //row0.CreateCell(10).SetCellValue("FOrderPrice");
            //row0.CreateCell(11).SetCellValue("fnetweight");
            //row0.CreateCell(10).SetCellValue("FGrossWeight");
            //row0.CreateCell(10).SetCellValue("bom层级");  
                int k = 1;
                foreach (DataRow item in dt.Rows)
                { 
                    NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(k);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        rowtemp.CreateCell(j).SetCellValue(item[j].ToString());  
                    }
                    k++; 
                }
  
 
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", HttpUtility.UrlEncode("导出数据" + itemid, Encoding.UTF8).ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");

        }
        /// <summary>
        /// 用于Bom管理主视图查询
        /// </summary>
        /// <returns></returns>
        public ActionResult GetBomItem()
        {
            //obtain the query para
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "FName" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];
            
            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量
           // string FBillNo = Request["FBillNo"] == null ? "" : Request["FBillNo"];
            string FName = Request["FName"] == null ? "" : Request["FName"]; 
            string FModel = Request["FModel"] == null ? "" : Request["FModel"];
            int fbominterid = string.IsNullOrWhiteSpace(Request["fbominterid"])? 0 : Convert.ToInt32( Request["fbominterid"]);
            if (fbominterid > 0)
            {
                strWhere += string.Format(" and a.fbominterid = {0}", fbominterid);
            }
            if (FName !="")
            {
                strWhere += string.Format(" and b.FName like '%{0}%'",FName);
            }
            if (FModel!="")
            {
                 strWhere += string.Format(" and b.FModel like '%{0}%'",FModel);
            }

            int totalCount;
            string tablename = "icbom a left join t_ICITEMCORE b on a.FItemID=b.FItemID left join t_icitemdesign c on  a.FItemID=c.FItemID left join t_ICItemStandard d on a.FItemID=d.FItemID";
            string innercolumns = "a.FInterID as bomID,a.FItemID,a.FHEADSELFZ0132 as itemPrice,d.FstandardManHour as worktime,b.FName,b.FModel,b.FNumber,b.FOrderPrice,c.fnetweight,c.FGrossWeight";
            string outcolumns = "bomID,FItemID,FName,FModel,FNumber,itemPrice,worktime,fnetweight,FOrderPrice,FGrossWeight";
            string sort1 = "a.FInterID desc";
            DataTable dt = SqlHelper.GetPagerDataTable(tablename, innercolumns, outcolumns, pageindex, pagesize, strWhere, sort1, out totalCount, true);
            string strJson = JsonHelper.ToJson(dt);
            string content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            return Content(content);
        }


    }
}
